package com.qf.smsplatform.controller;

import com.qf.smsplatform.service.InterfaceService;
import com.qf.smsplatform.util.R;
import com.qf.smsplatform.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 接收下行接口的Controller
 */
@RestController
public class InterfaceController {

    @Autowired
    private InterfaceService interfaceService;

    @RequestMapping("/smsInterface")
    public ResultVO smsInterface(@RequestBody Map map, HttpServletRequest request){
        //1. 接收客户端真实的IP地址.(客户端请求经过了Nginx反向代理服务器,正常情况无法通过request.getRemoteAdd获取)
        String ip = this.getRealRemoteAddr(request);

        //2. 封装到map集合中
        map.put("ip",ip);

        //3. 调用service层校验6个参数
        interfaceService.checkParameterAndSendMessage2MQ(map);

        //4. 返回信息
        return R.ok();
    }



    /**
     *
     * @param request
     * @author 你自己
     * @return
     */
    public String getRealRemoteAddr(HttpServletRequest request) {
        //如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值
        String ip = request.getHeader("X-Forwarded-For");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        //apache http做代理时一般会加上Proxy-Client-IP请求头
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        //apache http做代理时，weblogic插件加上WL-Proxy-Client-IP。
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        //部分代理服务器加的请求头
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        //分代理服务器加的请求头
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        //nginx代理一般会加上此请求头
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        //当不使用代理获取的ip
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
    }

}
